/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.formserver.vmmanager;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.edp.formserver.viewmodel.Context;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.VoThreadLoacl;
import com.inspur.edp.lcm.metadata.api.IMetadataContent;
import com.inspur.edp.lcm.metadata.spi.MetadataContentSerializer;

import java.io.IOException;

/**
 * @author shksatrt
 * @DATE 2019/7/29 - 10:12
 */
public class ContentSerializer implements MetadataContentSerializer {

	@Override
	public JsonNode Serialize(IMetadataContent iMetadataContent) {
		Context context = new Context();
		context.setfull(false);
		VoThreadLoacl.set(context);
		try {
			String json = new ObjectMapper().writeValueAsString(iMetadataContent);
			JsonNode jsonNode = new ObjectMapper().readTree(json);
			return jsonNode;
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (RuntimeException e) {
			throw new RuntimeException(e + ((GspViewModel) iMetadataContent).getGeneratingAssembly(), e);
		}finally {
			VoThreadLoacl.unset();
		}
	}

	@Override
	public IMetadataContent DeSerialize(JsonNode jsonNode) {
		ObjectMapper mapper = new ObjectMapper();
		try {
      GspViewModel vm=mapper.readValue(handleJsonString(jsonNode.toString()), GspViewModel.class);
//      if(RefCommonContext.isInvokeAtDesignTime()){
//        if (vm.getMainObject().getMapping() != null && vm.getMainObject().getMapping().getSourceType() == GspVoObjectSourceType.BeObject) {
//          LinkBeUtils linkUtil = new LinkBeUtils();
//          linkUtil.linkWithBe(vm);
//        }
//      }
      return vm;
		} catch (IOException e) {
      throw new RuntimeException("vo元数据反序列化失败"+e);
		}
	}

	private static String handleJsonString(String contentJson) {
		if (contentJson.startsWith("\"")) {
			contentJson = contentJson.replace("\\\"", "\"");
			while (contentJson.startsWith("\"")) {
				contentJson = contentJson.substring(1, contentJson.length() - 1);
			}
		}
		return contentJson;
	}
}
